package cn.cloudreal.cbms.Dictionary.action;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import cn.cloudreal.cbms.Dictionary.service.DictionaryService;
import cn.cloudreal.cbms.common.util.Constants;
import cn.cloudreal.cbms.common.util.PageBean;
import cn.cloudreal.cbms.vo.Dictionary;

import com.opensymphony.xwork2.ActionSupport;

/**
 * <p>
 * Title: CBMS
 * </p>
 * <p>
 * Description:权限管理查询数据服务层视图类
 * </p>
 * <p>
 * Copyright: Copyright (c) 2012
 * </p>
 * <p>
 * Company:云恒瑞通
 * </p>
 * 
 * @author Gaoxuejiao
 * @date 2012-07-17
 */
public class DictionaryAction extends ActionSupport
{
    /** serialVersionUID */
    private static final long serialVersionUID = 1L;

    /** 日志工具类实例 */
    private static final Logger log = Logger.getLogger(DictionaryAction.class);

    /**
     * 注入service 类
     */
    private DictionaryService dictionaryService;
    
    public DictionaryService getDictionaryService() {
		return dictionaryService;
	}

	public void setDictionaryService(DictionaryService dictionaryService) {
		this.dictionaryService = dictionaryService;
	}

    /** id */
    long id;

    /** 当前页 */
    int currentPage;

    /** 组织架构列表 */
    private List<Dictionary> dictionaryLists;

    /**
     * 用户实体信息
     */
    private Dictionary dictionary;

    /** 分页对象 */
    PageBean page;

    /** falg：1：查看，2：修改初始化，3：修改确认 ，4：新增保存 */
    String flag;

    /**
     * 查询出数据字典
     * 并转换成JSON串
     * 给Ztree展示
     * @return String
     */
    public String getDictionaryList()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter DictionaryArction list() method,return String");
        }
        try
        {
        	
            dictionaryLists = new ArrayList<Dictionary>();
            // 获取集合
            dictionaryLists = dictionaryService.getAllDictionarys();

            StringBuffer ss = new StringBuffer("[");
            for (int i = 0; i < dictionaryLists.size(); i++)
            {
                if (i == 0)
                {
                    // 获取第一个 节点权限详情
                    dictionary = dictionaryLists.get(i);
                }
                // 获取集合单独对象 
                Dictionary dic = new Dictionary();
                dic = dictionaryLists.get(i);
                // 如果当前是父节点打开
                if (dic.getParentId() == -1)
                {
                    ss.append("{ id:'" + dic.getId() + "',  pId:"
                            + dic.getParentId() + ",   name:'"
                            + dic.getClassname() + "',open:true},");
                }
                else
                {
                    ss.append("{ id:'" + dic.getId() + "',  pId:"
                            + dic.getParentId() + ",   name:'"
                            + dic.getClassname() + "'},");
                }
            }
            if (null != dictionaryLists && dictionaryLists.size() > 0)
            {
                // 获取第一个节点详情
                flag = ss.substring(0, ss.toString().length() - 1).toString();

            }
            else
            {
                flag = ss.toString(); 
            }
            flag += "];";
            System.out.println("flag------------------->"+flag);
        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常信息 返回error
            log.error("Error DictionaryArction list() method,return String", e);
            return ERROR;
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit DictionaryArction list() method,return String");
        }
        return SUCCESS;
    }

    //新增数据字典
    public String doDictionaryAdd()
   {
      // 打印进入方法体日志
      if (log.isInfoEnabled())
      {
          log.info("Enter DictionaryArction save() method,return String");
      }

      // response 对象
      HttpServletResponse response = ServletActionContext.getResponse();
      PrintWriter out = null;
      try
      {
          // 获取PrintWriter对象
          ServletActionContext.getRequest()
                  .setCharacterEncoding(Constants.STR_UTF);
          response.setContentType(Constants.STR_CHARSET);
          out = response.getWriter();

          // 非空判断
          if (null != dictionary && null != dictionary.getClasscode())
          {
        	  
        	  System.out.println("------>"+dictionary);
              String temp = dictionary.getClasscode().trim();
              dictionary.setClasscode(temp.substring(0, temp.length() - 1));
              dictionaryService.save(dictionary);
              out.print("save dictionary");
              out.flush();
              out.close();
              return null;
          }
      }
      catch (Exception e)
      {
          log.error("Error DictionaryArction  doAddPurview() method,return String ",
                  e);
          // return ERROR;
          out.print("error");
          out.flush();
          out.close();
          return null;
      }

      // 打印退出方法体日志
      if (log.isInfoEnabled())
      {
          log.info("Exit DictionaryArction  doAddPurview() method,return String ");
      }
      return null;
  }

  /**
  * 删除
  * 
  * @return SUCCESS
  */
 public String deleteDictionary()
 {
     // 打印进入方法体日志
     if (log.isInfoEnabled())
     {
         log.info("Enter DictionaryArction delete() method,return String");
     }

     // response 对象
     HttpServletResponse response = ServletActionContext.getResponse();
     PrintWriter out = null;
     try
     {
         // 获取PrintWriter对象
         ServletActionContext.getRequest()
                 .setCharacterEncoding(Constants.STR_UTF);
         response.setContentType(Constants.STR_CHARSET);
         out = response.getWriter();
         // 如果不为空 执行查询
         if (null != dictionary)
         {
             // 验证当前权限节点是否正在使用
             if (dictionaryService.isUseDictionary(dictionary.getId()))
             {
                 out.print("false");
                 out.flush();
                 out.close();
                 return null;
             }
             else
             {
                 dictionaryService.delete(dictionary);
                 out.print("true");
                 out.flush();
                 out.close();

                 return null;
             }

         }
     }
     catch (Exception e)
     {
         log.error("Error DictionaryArction delete() method,return String", e);
         // return ERROR;
         out.print("error");
         out.flush();
         out.close();
         return null;
     }

     // 打印退出方法体日志
     if (log.isInfoEnabled())
     {
         log.info("Exit DictionaryArction delete() method,return String ");
     }
     return null;
 }    
    
    
    
    
    
    /**
     * 查看数据字典详情
     * 
     * @return
     */
    public String dictionaryDetail()
    {
       
    	
    	List<Dictionary> list = dictionaryService.findByParentId(-1);
    	for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Dictionary dictionary = (Dictionary) iterator.next();
			System.out.println(dictionary);
		}
    	
    	
    	
    	// 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter DictionaryArction view() method,return String");
        }
        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();

            // 如果不为空 执行查询
            if (null != dictionary)
            {
                dictionary = dictionaryService.findByID(dictionary.getId());
                Map map = new HashMap<Object, Object>();
                map.put("dictionary", dictionary);

                JSONArray jo = JSONArray.fromObject(map);

                out.print(jo.toString());
                out.flush();
                out.close();
                return null;
            }
        }
        catch (Exception e)
        {
            log.error("Error DictionaryArction view() method,return String edit", e);
            // return ERROR;
            Map map = new HashMap<Object, Object>();
            map.put("msg", "error");

            JSONArray jo = JSONArray.fromObject(map);

            out.print(jo.toString());
            out.flush();
            out.close();
            return null;
        }
        return null;
    }
    

    /**
     * 跳转到修改页面
     * 
     * @return SUCCESS
     */
    public String doDictionaryEdit()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter DictionaryArction view() method,return String");
        }
        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();

            if (null != dictionary)
            {
System.out.println("edit"+dictionary);
                dictionaryService.update(dictionary);
                out.print("true");
                out.flush();
                out.close();
                return null;
            }
        }
        catch (Exception e)
        {
            log.error("Error DictionaryArction view() method,return String edit", e);
            // return ERROR;
            out.print("error");
            out.flush();
            out.close();
            return null;
        }
        return null;
    }



    /**
     * 验证当前 编号是否已经存在
     * 
     * @return SUCCESS
     */
    public String isExistDictionaryCode()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter DictionaryArction isExistUsePurCode() method,return String");
        }

        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();

            // 非空判断
            if (null != dictionary && null != dictionary.getClasscode())
            {
//System.out.println("before---->isExistDictionaryCode="+dictionary);
                Dictionary result = dictionaryService.findByClassCode(dictionary.getClasscode(), null);
//System.out.println("after----->"+result);
                if (null != result )
                {
                    out.print("true");
                    out.flush();
                    out.close();
                    return null;
                }
            }
        }
        catch (Exception e)
        {
            // TODO: handle exception
            // 打印方法体异常日志
            log.error("Error DictionaryArction  isExistUsePurCode() method,return String ",
                    e);
            // return ERROR;
            out.print("error");
            out.flush();
            out.close();
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit DictionaryArction  isExistUsePurCode() method,return String ");
        }
        return null;
    }

    /**
     * 验证当前 名称是否已经存在
     * 
     * @return SUCCESS
     */
    public String isExistDictionaryName()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter DictionaryArction isExistUsePurName() method,return String");
        }

        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();

            // 非空判断
            if (null != dictionary && null != dictionary.getClassname())
            {
System.out.println("isExistDictionaryName="+dictionary);
                Dictionary result = dictionaryService.findByClassName(dictionary.getClassname());
System.out.println("result="+result);
                if (null != result )
                {
                    out.print("true");
                    out.flush();
                    out.close();
                    return null;
                }
            }
        }
        catch (Exception e)
        {
            // TODO: handle exception
            // 打印方法体异常日志
            log.error("Error DictionaryArction  isExistUsePurName() method,return String ",
                    e);
            out.print("error");
            out.flush();
            out.close();
            // return ERROR;
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit DictionaryArction  isExistUsePurName() method,return String ");
        }
        return null;
    }

    public int getCurrentPage()
    {
        return currentPage;
    }

    public void setCurrentPage(int currentPage)
    {
        this.currentPage = currentPage;
    }

    public long getId()
    {
        return id;
    }

    public void setId(long id)
    {
        this.id = id;
    }

    public String getFlag()
    {
        return flag;
    }

    public void setFlag(String flag)
    {
        this.flag = flag;
    }

    public PageBean getPage()
    {
        return page;
    }

    public void setPage(PageBean page)
    {
        this.page = page;
    }

    

    public List<Dictionary> getDictionaryLists() {
		return dictionaryLists;
	}

	public void setDictionaryLists(List<Dictionary> dictionaryLists) {
		this.dictionaryLists = dictionaryLists;
	}

	public Dictionary getDictionary() {
		return dictionary;
	}

	public void setDictionary(Dictionary dictionary) {
		this.dictionary = dictionary;
	}

	

}
